import React, { useState, useEffect } from 'react';
import { Table, Modal, Form, Input, Tree, Space, message, Spin, Alert, Button, Tag, Select, Row, Col } from 'antd';
import type { TreeProps, DataNode } from 'antd/lib/tree';
import { DeleteOutlined, EditOutlined, ExclamationCircleOutlined, PlusOutlined, ReloadOutlined, InfoCircleOutlined, StopOutlined } from '@ant-design/icons';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { getRoleList, addRole, updateRole, deleteRole, updateRoleRights } from '../../../api/roleApi';
import { getRights } from '../../../api';
import type { Role } from '../../../types';
import useSimpleAuth from '../../../hooks/useSimpleAuth';
import SimplePermissionButton from '../../../components/permission/SimplePermissionButton';
import { STORAGE_KEYS, ROLE_TYPES } from '../../../constants/common';
import { useNavigate } from 'react-router-dom';
import './RoleList.scss';
import auth from '../../../utils/auth';
import { store } from '../../../store';

const { Option } = Select;

/**
 * 获取角色的唯一ID，兼容MongoDB格式
 * @param role 角色项
 * @returns 用于表格rowKey的唯一标识
 */
const getRoleId = (role: Role): string => {
  // 优先使用MongoDB的_id
  if (role._id) {
    return role._id;
  }
  
  // 其次使用id字段
  if (typeof role.id === 'string' || typeof role.id === 'number') {
    return role.id.toString();
  }
  
  // 最后使用seqId或其他可能的唯一标识
  return role.seqId?.toString() || Math.random().toString();
};

// 角色类型名称映射
const roleTypeNames = {
  [ROLE_TYPES.SUPER_ADMIN]: '超级管理员',
  [ROLE_TYPES.ADMIN]: '管理员',
  [ROLE_TYPES.EDITOR]: '编辑'
};

// 获取角色类型名称
const getRoleTypeName = (roleType: number): string => {
  return roleTypeNames[roleType] || '未知角色';
};

// 获取角色类型颜色
const getRoleTypeColor = (roleType: number): string => {
  switch (roleType) {
    case ROLE_TYPES.SUPER_ADMIN:
      return 'red';
    case ROLE_TYPES.ADMIN:
      return 'blue';
    case ROLE_TYPES.EDITOR:
      return 'green';
    default:
      return 'default';
  }
};

const RoleList: React.FC = () => {
  const [form] = Form.useForm();
  const [currentRole, setCurrentRole] = useState<Role | null>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isRightsModalOpen, setIsRightsModalOpen] = useState(false);
  const [checkedKeys, setCheckedKeys] = useState<string[]>([]);
  const queryClient = useQueryClient();
  const navigate = useNavigate();
  
  // 使用简化版权限钩子
  const { isSuperAdmin } = useSimpleAuth();

  // 如果不是超级管理员，重定向到首页
  useEffect(() => {
    if (!isSuperAdmin()) {
      message.error('您没有权限访问该页面');
      navigate('/home');
    }
  }, [isSuperAdmin, navigate]);

  // 获取角色列表数据
  const { data: roleList, isLoading: isRolesLoading, error: rolesError, refetch: refetchRoles } = useQuery({
    queryKey: ['roles'],
    queryFn: async () => {
      try {
        console.log('重新获取角色列表数据');
        const res = await getRoleList();
        console.log('角色列表API响应:', res); // 调试日志
        
        return res; // API直接返回Role[]
      } catch (err) {
        console.error('获取角色列表失败:', err);
        throw err;
      }
    },
    staleTime: 0, // 禁用缓存
    refetchOnMount: true, // 组件挂载时重新获取
    refetchOnWindowFocus: true // 窗口获得焦点时重新获取
  });

  // 获取权限列表数据
  const { data: rightsList, isLoading: isRightsLoading, error: rightsError, refetch: refetchRights } = useQuery({
    queryKey: ['rights'],
    queryFn: async () => {
      try {
        console.log('重新获取权限树数据');
        const res = await getRights();
        console.log('权限列表API响应 (Tree数据):', res); // 调试日志
        
        return res; // API直接返回Right[]
      } catch (err) {
        console.error('获取权限列表失败:', err);
        throw err;
      }
    },
    staleTime: 0, // 禁用缓存
    refetchOnMount: true, // 组件挂载时重新获取
    refetchOnWindowFocus: true // 窗口获得焦点时重新获取
  });
  
  // 添加路由监听，每次路由到此页面都重新获取数据
  useEffect(() => {
    console.log('RoleList组件挂载或更新，重新获取数据');
    refetchRoles();
    refetchRights();
  }, [refetchRoles, refetchRights]);

  // 添加调试日志
  useEffect(() => {
    if (roleList) {
      console.log('处理后的角色列表数据:', roleList);
    }
    if (rightsList) {
      console.log('处理后的权限树数据:', rightsList);
    }
    if (rolesError || rightsError) {
      console.error('数据加载错误:', rolesError || rightsError);
    }
  }, [roleList, rightsList, rolesError, rightsError]);

  // 添加角色
  const addRoleMutation = useMutation({
    mutationFn: (values: { roleName: string, roleType: number }) => 
      addRole({ roleName: values.roleName, roleType: values.roleType }),
    onSuccess: () => {
      message.success('添加角色成功');
      form.resetFields();
      setIsModalOpen(false);
      queryClient.invalidateQueries({ queryKey: ['roles'] });
    }
  });

  // 更新角色
  const updateRoleMutation = useMutation({
    mutationFn: (values: { id: number | string; roleName: string, roleType: number }) => 
      updateRole(values.id, { roleName: values.roleName, roleType: values.roleType }),
    onSuccess: () => {
      message.success('更新角色成功');
      form.resetFields();
      setIsModalOpen(false);
      queryClient.invalidateQueries({ queryKey: ['roles'] });
    }
  });

  // 删除角色
  const deleteRoleMutation = useMutation({
    mutationFn: (id: number | string) => deleteRole(id),
    onSuccess: () => {
      message.success('删除角色成功');
      queryClient.invalidateQueries({ queryKey: ['roles'] });
    }
  });

  // 更新角色权限
  const updateRightsMutation = useMutation({
    mutationFn: ({ roleId, rights }: { roleId: number | string; rights: string[] }) => 
      updateRoleRights(roleId, rights),
    onSuccess: () => {
      message.success('权限分配成功');
      setIsRightsModalOpen(false);
      queryClient.invalidateQueries({ queryKey: ['roles'] });
    }
  });

  const showModal = (record?: Role) => {
    if (record) {
      setCurrentRole(record);
      form.setFieldsValue({
        roleName: record.roleName,
        roleType: record.roleType
      });
    } else {
      setCurrentRole(null);
      form.resetFields();
    }
    setIsModalOpen(true);
  };

  const showRightsModal = (record: Role) => {
    setCurrentRole(record);
    // 假设rights是一个对象数组，每个对象有一个key属性
    // 使用类型断言或可选链避免类型错误
    const keys = record.rights?.map(right => {
      if (typeof right === 'string') return right;
      // @ts-expect-error - 兼容可能的不同字段名
      return right.key || right.id?.toString() || '';
    }) || [];
    setCheckedKeys(keys);
    setIsRightsModalOpen(true);
  };

  const handleOk = () => {
    form.validateFields().then(values => {
      if (currentRole) {
        updateRoleMutation.mutate({ 
          id: currentRole.id, 
          roleName: values.roleName,
          roleType: values.roleType
        });
      } else {
        addRoleMutation.mutate(values);
      }
    });
  };

  const handleRightsOk = () => {
    if (currentRole) {
      updateRightsMutation.mutate({ 
        roleId: currentRole.id, 
        rights: checkedKeys 
      });
    }
  };

  const handleDelete = (record: Role) => {
    Modal.confirm({
      title: '警告',
      icon: <ExclamationCircleOutlined style={{ color: 'red' }} />,
      content: (
        <div>
          <p><strong>您确定要删除角色 "{record.roleName}" 吗？</strong></p>
          <p>此操作将会影响拥有该角色的所有用户，请慎重操作！</p>
        </div>
      ),
      okText: '确认删除',
      okButtonProps: { danger: true },
      cancelText: '取消',
      onOk: () => deleteRoleMutation.mutate(record.id)
    });
  };

  // 修复onCheck类型，使用antd的TreeProps类型
  const onCheck: TreeProps['onCheck'] = (checkedKeysValue) => {
    console.log('Tree选中的权限:', checkedKeysValue); // 调试日志
    
    // 将选中的键转换为字符串数组
    const keys: string[] = [];
    
    if (Array.isArray(checkedKeysValue)) {
      checkedKeysValue.forEach(key => {
        keys.push(String(key));
      });
    } else if (checkedKeysValue && typeof checkedKeysValue === 'object' && 'checked' in checkedKeysValue) {
      checkedKeysValue.checked.forEach(key => {
        keys.push(String(key));
      });
    }
    
    setCheckedKeys(keys);
  };

  const columns = [
    {
      title: 'ID',
      dataIndex: 'seqId',
      key: 'seqId',
      render: (seqId: string | number) => <b>{seqId}</b>
    },
    {
      title: '角色名称',
      dataIndex: 'roleName',
      key: 'roleName'
    },
    {
      title: '角色类型',
      dataIndex: 'roleType',
      key: 'roleType',
      render: (roleType: number) => (
        <Tag color={getRoleTypeColor(roleType)}>
          {getRoleTypeName(roleType)}
        </Tag>
      )
    },
    {
      title: '操作',
      key: 'action',
      render: (_: unknown, record: Role) => {
        // 判断是否是超级管理员角色
        const isSuperAdminRole = record.roleType === ROLE_TYPES.SUPER_ADMIN || 
                                 record.roleName === '超级管理员';
        
        return (
          <Space size="middle">
            <SimplePermissionButton 
              type="primary" 
              shape="circle" 
              icon={<EditOutlined />} 
              onClick={() => showModal(record)}
              permission="update.role"
              disableOnNoPermission={false} // 临时禁用权限检查限制
              tooltipTitle="编辑角色"
              disabled={isSuperAdminRole} // 仍保留对超级管理员角色的禁用
            />
            <SimplePermissionButton 
              type="primary" 
              danger 
              shape="circle" 
              icon={<DeleteOutlined />} 
              onClick={() => handleDelete(record)}
              permission="delete.role"
              disableOnNoPermission={false} // 临时禁用权限检查限制
              tooltipTitle="删除角色"
              disabled={isSuperAdminRole} // 仍保留对超级管理员角色的禁用
            />
            <SimplePermissionButton 
              type="primary" 
              onClick={() => showRightsModal(record)}
              permission="assign.role.rights"
              disableOnNoPermission={false} // 临时禁用权限检查限制
              tooltipTitle="分配权限"
            >
              权限设置
            </SimplePermissionButton>
          </Space>
        );
      }
    }
  ];

  // 处理加载状态
  const isLoading = isRolesLoading || isRightsLoading;
  const hasError = rolesError || rightsError;

  if (isLoading && !hasError) {
    return (
      <div className="role-list-container">
        <div className="loading-container">
          <Spin size="large" tip="加载角色数据中..." />
        </div>
      </div>
    );
  }

  // 确保数据为数组
  const roleData = roleList || [];

  // 处理应用权限变更
  const handleApplyPermissionChanges = () => {
    // 获取当前用户信息
    const currentUser = auth.getUserInfo();
    
    if (!currentUser) {
      message.error('未能获取当前用户信息，请重新登录');
      return;
    }
    
    // 获取当前用户角色ID
    const roleId = currentUser.roleId || (currentUser.role && currentUser.role.id);
    
    if (!roleId) {
      message.error('未能获取当前用户角色信息');
      return;
    }
    
    // 查找当前用户的角色在角色列表中的最新权限
    const userRole = roleList?.find(role => 
      role.id === roleId || 
      role._id === roleId || 
      String(role.id) === String(roleId) ||
      String(role._id) === String(roleId)
    );
    
    if (!userRole || !userRole.rights) {
      message.error('未能找到当前用户角色的权限信息');
      return;
    }
    
    console.log('找到当前用户角色:', userRole);
    console.log('最新权限列表:', userRole.rights);
    
    // 清除权限相关缓存
    localStorage.removeItem(STORAGE_KEYS.USER_RIGHTS);
    
    // 确保PERMISSIONS键存在且为字符串
    if (STORAGE_KEYS.PERMISSIONS && typeof STORAGE_KEYS.PERMISSIONS === 'string') {
      localStorage.removeItem(STORAGE_KEYS.PERMISSIONS);
    }
    
    // 使用auth工具更新权限
    auth.setUserRights(userRole.rights);
    
    // 更新Redux状态
    if (store.dispatch) {
      store.dispatch({ type: 'user/setRights', payload: userRole.rights });
    }
    
    // 更新当前用户对象中的权限
    if (currentUser.role) {
      currentUser.role.rights = userRole.rights;
      auth.setUserInfo(currentUser);
    }
    
    // 显示成功消息
    message.success('角色权限已更新，应用新权限...');
    
    // 延迟一下再刷新侧边栏菜单，让用户看到提示
    setTimeout(() => {
      // 触发一个React状态更新，而不是强制刷新整个页面
      queryClient.invalidateQueries({ queryKey: ['roles'] });
      queryClient.invalidateQueries({ queryKey: ['rights'] });
      
      // 使用条件渲染来触发SideMenu重新渲染
      setIsRightsModalOpen(false);
    }, 1000);
  };

  // 如果用户不是超级管理员，显示权限不足提示
  if (!isSuperAdmin()) {
    return (
      <div style={{ padding: '50px', textAlign: 'center' }}>
        <h2><StopOutlined style={{ color: 'red' }} /> 权限不足</h2>
        <p>只有超级管理员才能访问角色管理页面</p>
        <Button type="primary" onClick={() => navigate('/home')}>
          返回首页
        </Button>
      </div>
    );
  }

  return (
    <div className="role-list-container">
      {hasError && (
        <div style={{ color: 'red', marginBottom: '16px' }}>
          加载角色列表出错，请刷新页面重试
        </div>
      )}
      
      {/* 添加权限提示信息 */}
      <Alert
        message="角色管理 - 根据角色分配系统权限"
        description="在这里您可以管理系统角色，并为不同角色分配对应的权限。角色设置将直接影响用户可以查看和操作的内容。"
        type="info"
        showIcon
        style={{ marginBottom: 16 }}
      />
      
      {/* 添加权限更新按钮 */}
      <div style={{ 
        margin: '20px 0', 
        padding: '10px 15px', 
        background: '#f0f9ff', 
        border: '1px solid #91caff',
        borderRadius: '4px'
      }}>
        <Row align="middle" justify="space-between">
          <Col>
            <p style={{ margin: 0 }}>
              <InfoCircleOutlined style={{ marginRight: '8px', color: '#1677ff' }} />
              <span>如果您修改了角色权限，需要刷新页面才能应用这些更改。</span>
            </p>
          </Col>
          <Col>
            <Space>
              <Button 
                type="primary"
                onClick={handleApplyPermissionChanges}
                icon={<ReloadOutlined />}
              >
                应用权限变更
              </Button>
            </Space>
          </Col>
        </Row>
      </div>
      
      <SimplePermissionButton 
        type="primary" 
        icon={<PlusOutlined />}
        onClick={() => showModal()} 
        style={{ marginBottom: 16 }}
        permission="add.role"
        tooltipTitle="添加新角色"
      >
        添加角色
      </SimplePermissionButton>
      
      <Table
        dataSource={roleData}
        columns={columns}
        rowKey={getRoleId}
        pagination={{ pageSize: 5 }}
        locale={{ emptyText: '暂无数据' }}
      />
      
      <Modal
        title={currentRole ? "编辑角色" : "添加角色"}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={() => setIsModalOpen(false)}
        confirmLoading={addRoleMutation.isPending || updateRoleMutation.isPending}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="roleName"
            label="角色名称"
            rules={[{ required: true, message: '请输入角色名称' }]}
          >
            <Input placeholder="请输入角色名称" />
          </Form.Item>
          <Form.Item
            name="roleType"
            label="角色类型"
            rules={[{ required: true, message: '请选择角色类型' }]}
            initialValue={ROLE_TYPES.EDITOR} // 默认为编辑角色
          >
            <Select placeholder="请选择角色类型">
              {!currentRole?.roleType || currentRole?.roleType !== ROLE_TYPES.SUPER_ADMIN ? (
                <>
                  <Option value={ROLE_TYPES.ADMIN}>管理员</Option>
                  <Option value={ROLE_TYPES.EDITOR}>编辑</Option>
                </>
              ) : (
                <Option value={ROLE_TYPES.SUPER_ADMIN}>超级管理员</Option>
              )}
            </Select>
          </Form.Item>
        </Form>
      </Modal>
      
      <Modal
        title="权限分配"
        open={isRightsModalOpen}
        onOk={handleRightsOk}
        onCancel={() => setIsRightsModalOpen(false)}
        confirmLoading={updateRightsMutation.isPending}
        width={600}
      >
        <Alert
          message={`正在为角色 "${currentRole?.roleName || ''}" 分配权限`}
          description="请在下方树形结构中选择该角色可以拥有的权限，勾选的权限将在用户界面中显示。"
          type="info"
          showIcon
          style={{ marginBottom: 16 }}
        />
        <div className="tree-container">
          {rightsList ? (
            <Tree
              checkable
              className="rights-tree"
              checkedKeys={checkedKeys}
              onCheck={onCheck}
              treeData={rightsList as unknown as DataNode[]}
            />
          ) : (
            <div style={{ textAlign: 'center', padding: '20px' }}>
              无权限数据或数据格式错误
            </div>
          )}
        </div>
      </Modal>
    </div>
  );
};

export default RoleList; 